package org.my.stock.h2;

import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.my.stock.h2.model.MMaiDian;
import org.my.stock.h2.util.BrotliHttpClientHelper;
import org.my.stock.h2.util.MyUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MyDongFangStockH2 {

    public static String getUrl_update(String symbol) {
        StringBuilder sb = new StringBuilder();
        //sb.append("https://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get?cb=jQuery112308788068735906851_1744518781844&lmt=0&klt=101&fields1=f1%2Cf2%2Cf3%2Cf7&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61%2Cf62%2Cf63%2Cf64%2Cf65&ut=b2884a393a59ad64002292a3e90d46a5&secid=");
        sb.append("https://push2his.eastmoney.com/api/qt/stock/kline/get?cb=jQuery351015384170593978097_1747740474672&secid=");
        if (symbol.startsWith("3") || symbol.startsWith("00") || symbol.startsWith("4") || symbol.startsWith("8")) {
            sb.append("0." + symbol + "&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&end=20500101&lmt=120&_=1747740474682");
        } else if (symbol.startsWith("2") || symbol.startsWith("9")) {
            return null;
        }
        else {
            sb.append("1." + symbol + "&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1%2Cf2%2Cf3%2Cf4%2Cf5%2Cf6&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61&klt=101&fqt=1&end=20500101&lmt=120&_=1747740474682");
        }
        //return String.format("https://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get?cb=jQuery112308788068735906851_1744518781844&lmt=0&klt=101&fields1=f1%2Cf2%2Cf3%2Cf7&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61%2Cf62%2Cf63%2Cf64%2Cf65&ut=b2884a393a59ad64002292a3e90d46a5&secid=0.%s&_=1744518781845", symbol);
        return sb.toString();
    }

    public static void updateAll_ex() throws SQLException, ClassNotFoundException {

        Connection conn = MyUtil.getConnection();

        String sql = "SELECT symbol FROM type_stock GROUP BY symbol";
        PreparedStatement stmt = conn.prepareStatement(sql);
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            getData_ex(conn, rs.getString(1));
        }

        if (rs != null) rs.close();
        if (stmt != null) stmt.close();
        if (conn != null) conn.close();
    }

    public static void getData_ex(Connection conn, String symbol) {
        String url = getUrl_update(symbol);
        if (url != null) {
            HttpClient httpClient = BrotliHttpClientHelper.createBrotliClient();

            try {
                // 1. 创建 GET 请求
                HttpGet request = new HttpGet(url);

                // 2. 设置请求头（防止被服务器拒绝）
                request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");
                request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
                request.setHeader("Accept-Encoding", "gzip, deflate, br");
                request.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
                request.setHeader("Cache-Control", "max-age=0");
                request.setHeader("Connection", "keep-alive");
                request.setHeader("Cookie", "em_hq_fls=js; intellpositionL=1140px; em-quote-version=topspeed; intellpositionT=1298px; qgqp_b_id=e04e31a1e6446068e54e0f7808401919; sid=142772185; mtp=1; ct=oFv-pht6ZiYeFSXV2tPdRfkJ0x6ZftJa4X2TKji2eXO0Pl_YBbWxGBEwUTJ4z6N0GPPyYYrAizsB50OwF5PQc3x4HESZOAriGonI9ewh-RikgY0SEGHZcdA5RKg5RB4dPVIr3TCQLKkZkYOXQKFQElZVysNazqJ5O7csdsQO8U8; ut=FobyicMgeV5FJnFT189SwH2JOfiEw7mPz0LG7-oku6sFYOCxdbsEi2cnDTMMTwLC08VTgq_y28iF-S7gffFe0HKuLD1gS302VWRzT3pl7pFn5lPVWP0FGEkMzX3xkH4zZ26gwPXYW-E0EBZ8yNwMjA61nTdT3wPUm2MO4K_-pv5FU7C4OKwrxdk0UuppgrEnJEgArYW9ONwiZM25_K7mvoROgdu_rvCGeunwxnPYxpGqdl5zugvVg1iYtj7NhgcPysSINh74Fg1SOz2r1EMofNQ2h17qfzYUEa1h5_9kJkiB1FoE_P6A7kqYkMsr92-xF4fQoC_luUS273FRQNpqdmsbdOgZn9GV; pi=5274385825271944%3Bc5274385825271944%3B%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90%3BdCmpCdx6Fv0K9ySmGo1L60bQl9guPYNF9kW50ggeyA%2BOOeqCGeepIZPP0w088pbSCmH3QEBcYqyucZR9kKKJ4yNWHFBnnJznMgN%2F0PAMxp8Q%2FuJWZ89w97SHWrysOsb%2B93O45rM%2BhQroFhMO0X604MpHaHC%2F9yVsQmkbCVr5W1pviVaJGTOj%2FDWWzVmDAqUqGJzUNqW2%3BYeT6DxMds0uwdT3PftF0xut%2B1faguRkAY5Rpcphp0hhNyyGaYsTQbiMZEJxNWp7SrYuMigne0BGrZhWVS5SuyPZkN9SQHEd8yzBJUAbFcxV2So8rHP9l%2FY1Cf50pniZsBXw%2Bk0GvzjRxxPfbt9j1Vj8dTOWabw%3D%3D; vtpst=%7C; uidal=5274385825271944%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90; fullscreengg=1; fullscreengg2=1; st_si=66098437338071; emshistory=%5B%22%E6%BD%9E%E5%AE%89%E7%8E%AF%E8%83%BD%22%2C%22undefined%22%5D; HAList=ty-0-000893-%u4E9A%u94BE%u56FD%u9645%2Cty-90-BK0712-%u4E00%u5E26%u4E00%u8DEF%2Cty-1-600171-%u4E0A%u6D77%u8D1D%u5CAD%2Cty-90-BK0854-%u534E%u4E3A%u6982%u5FF5%2Cty-1-601398-%u5DE5%u5546%u94F6%u884C%2Cty-90-BK0968-%u56FA%u6001%u7535%u6C60%2Cty-0-300661-%u5723%u90A6%u80A1%u4EFD%2Cty-90-BK0638-%u521B%u4E1A%u6210%u4EFD%2Cty-1-601699-%u6F5E%u5B89%u73AF%u80FD%2Cty-0-300782-%u5353%u80DC%u5FAE; st_pvi=18633756697256; st_sp=2021-05-13%2015%3A20%3A17; st_inirUrl=https%3A%2F%2Fcn.bing.com%2F; st_sn=96; st_psi=2025041315314915-113300300815-4079987765; st_asi=delete");
                request.setHeader("Host", "push2his.eastmoney.com");
                request.setHeader("Sec-Fetch-Dest", "document");
                request.setHeader("Sec-Fetch-Mode", "navigate");
                request.setHeader("Upgrade-Insecure-Requests", "1");

                // 3. 执行请求并获取响应
                HttpResponse response = httpClient.execute(request);

                // 4. 检查状态码
                //int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("所属类型: " + symbol);

                // 5. 读取响应内容
                HttpEntity entity = response.getEntity();
                if (entity != null) {

                    // 关键：使用 UTF-8 编码转换解压后的字节流
                    String content = EntityUtils.toString(entity, "UTF-8");
                    //toDb(ignite, cache, content, type_name, day);
                    toDb_ex(conn, content, symbol);
                    System.out.println("解码内容:\n" + content);
                }

            } catch (Exception e) {
                System.err.println("请求失败: " + e.getMessage());
            } finally {
                // 6. 释放连接（重要！）
                httpClient.getConnectionManager().shutdown();
            }
        }
    }

    public static void toDb_ex(Connection conn, final String line, String symbol) throws SQLException {
        Pattern pattern = Pattern.compile("\\(([^)]+)\\)");
        Matcher matcher = pattern.matcher(line);

        if (matcher.find()) {
            String result = matcher.group(1); // 获取第一个捕获组内容

            LinkedTreeMap m = MyUtil.getGson().fromJson(result, new TypeToken<LinkedTreeMap>() {}.getType());
            LinkedTreeMap data = (LinkedTreeMap) m.get("data");
            List klines = (List) data.get("klines");
            //String name = (String) data.get("name");

            for (int i = klines.size() - 1; i >=  klines.size() - 20; i--) {
                System.out.println(klines.get(i).toString());
                String dl = klines.get(i).toString();
                String[] vs = dl.split(",");
                //List mt = MyUtil.getGson().fromJson(klines.get(i).toString(), new TypeToken<List>() {}.getType());
                //String sql = "insert into df_stock_date (symbol, price, main_fund, main_fund_bf, name, zhangdie, stock_date) values ('" + symbol + "', " + vs[11] + ", " + vs[1] + ", " + vs[6] + ", '" + name + "', " + vs[12] + ", '" + vs[0] + "')";
                //cache.query(new SqlFieldsQuery(sql)).getAll();
                // "2025-05-20,11.40,11.39,11.47,11.37,643635,734455265.82,0.88,0.18,0.02,0.33"
                updateDate_ex(conn, symbol, vs[7], vs[10], vs[0]);
            }
        }
    }

    /**
     * 判断 symbol 的数量是否是 20，如果不是 20，就修改最后一项的数据
     * "2025-05-20,11.40,11.39,11.47,11.37,643635,734455265.82,0.88,0.18,0.02,0.33"
     * price = vs[4]
     * main_fund = vs[4]
     * */
    public static void updateDate_ex(Connection conn, String symbol, String zhengfu, String huanshoulv, String stock_date) throws SQLException {
        // 修改最后一项的数据
        Long pkid = getSymbolLastId_ex(conn, symbol, stock_date);
        String sql = "update df_stock_date SET zhengfu = "+ zhengfu +", huanshoulv = "+ huanshoulv +" WHERE id = " + pkid.toString();
        //cache.query(new SqlFieldsQuery(sql)).getAll();
        Statement stmt = conn.createStatement();
        stmt.execute(sql);
    }

    /**
     * 获取 Symbol 的个数
     * */
    public static Long getSymbolLastId_ex(Connection conn, String symbol, String stock_date) {
        String sql = "select id from df_stock_date where symbol = '"+ symbol +"' and stock_date = '"+ stock_date +"'";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        long id = 0L;

        try {
            stmt = conn.prepareStatement(sql);

            // 5. 执行查询并获取结果集
            rs = stmt.executeQuery();

            // 6. 遍历结果集并处理数据
            while (rs.next()) {
                id = rs.getLong(1);
            }

        } catch (SQLException e) {
            System.err.println("数据库操作失败！错误信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 7. 关闭资源（反向顺序）
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return id;
    }

    public static String getUrl(String symbol) {
        StringBuilder sb = new StringBuilder();
        sb.append("https://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get?cb=jQuery112308788068735906851_1744518781844&lmt=0&klt=101&fields1=f1%2Cf2%2Cf3%2Cf7&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61%2Cf62%2Cf63%2Cf64%2Cf65&ut=b2884a393a59ad64002292a3e90d46a5&secid=");
        //sb.append("https://push2his.eastmoney.com/api/qt/stock/kline/get?cb=jQuery351015384170593978097_1747740474672&secid=");
        if (symbol.startsWith("3") || symbol.startsWith("00") || symbol.startsWith("4") || symbol.startsWith("8")) {
            sb.append("0." + symbol + "&_=1747740474682");
        } else if (symbol.startsWith("2") || symbol.startsWith("9")) {
            return null;
        }
        else {
            sb.append("1." + symbol + "&_=1747740474682");
        }
        //return String.format("https://push2his.eastmoney.com/api/qt/stock/fflow/daykline/get?cb=jQuery112308788068735906851_1744518781844&lmt=0&klt=101&fields1=f1%2Cf2%2Cf3%2Cf7&fields2=f51%2Cf52%2Cf53%2Cf54%2Cf55%2Cf56%2Cf57%2Cf58%2Cf59%2Cf60%2Cf61%2Cf62%2Cf63%2Cf64%2Cf65&ut=b2884a393a59ad64002292a3e90d46a5&secid=0.%s&_=1744518781845", symbol);
        return sb.toString();
    }

    public static void updateAll() throws SQLException, ClassNotFoundException {

        Connection conn = MyUtil.getConnection();

        String sql = "SELECT symbol FROM type_stock GROUP BY symbol";
        PreparedStatement stmt = conn.prepareStatement(sql);
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            getData(conn, rs.getString(1));
        }

        if (rs != null) rs.close();
        if (stmt != null) stmt.close();
        if (conn != null) conn.close();
    }

    public static void getData(Connection conn, String symbol) {
        String url = getUrl(symbol);
        if (url != null) {
            HttpClient httpClient = BrotliHttpClientHelper.createBrotliClient();

            try {
                // 1. 创建 GET 请求
                HttpGet request = new HttpGet(url);

                // 2. 设置请求头（防止被服务器拒绝）
                request.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36");
                request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
                request.setHeader("Accept-Encoding", "gzip, deflate, br");
                request.setHeader("Accept-Language", "zh-CN,zh;q=0.9");
                request.setHeader("Cache-Control", "max-age=0");
                request.setHeader("Connection", "keep-alive");
                request.setHeader("Cookie", "em_hq_fls=js; intellpositionL=1140px; em-quote-version=topspeed; intellpositionT=1298px; qgqp_b_id=e04e31a1e6446068e54e0f7808401919; sid=142772185; mtp=1; ct=oFv-pht6ZiYeFSXV2tPdRfkJ0x6ZftJa4X2TKji2eXO0Pl_YBbWxGBEwUTJ4z6N0GPPyYYrAizsB50OwF5PQc3x4HESZOAriGonI9ewh-RikgY0SEGHZcdA5RKg5RB4dPVIr3TCQLKkZkYOXQKFQElZVysNazqJ5O7csdsQO8U8; ut=FobyicMgeV5FJnFT189SwH2JOfiEw7mPz0LG7-oku6sFYOCxdbsEi2cnDTMMTwLC08VTgq_y28iF-S7gffFe0HKuLD1gS302VWRzT3pl7pFn5lPVWP0FGEkMzX3xkH4zZ26gwPXYW-E0EBZ8yNwMjA61nTdT3wPUm2MO4K_-pv5FU7C4OKwrxdk0UuppgrEnJEgArYW9ONwiZM25_K7mvoROgdu_rvCGeunwxnPYxpGqdl5zugvVg1iYtj7NhgcPysSINh74Fg1SOz2r1EMofNQ2h17qfzYUEa1h5_9kJkiB1FoE_P6A7kqYkMsr92-xF4fQoC_luUS273FRQNpqdmsbdOgZn9GV; pi=5274385825271944%3Bc5274385825271944%3B%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90%3BdCmpCdx6Fv0K9ySmGo1L60bQl9guPYNF9kW50ggeyA%2BOOeqCGeepIZPP0w088pbSCmH3QEBcYqyucZR9kKKJ4yNWHFBnnJznMgN%2F0PAMxp8Q%2FuJWZ89w97SHWrysOsb%2B93O45rM%2BhQroFhMO0X604MpHaHC%2F9yVsQmkbCVr5W1pviVaJGTOj%2FDWWzVmDAqUqGJzUNqW2%3BYeT6DxMds0uwdT3PftF0xut%2B1faguRkAY5Rpcphp0hhNyyGaYsTQbiMZEJxNWp7SrYuMigne0BGrZhWVS5SuyPZkN9SQHEd8yzBJUAbFcxV2So8rHP9l%2FY1Cf50pniZsBXw%2Bk0GvzjRxxPfbt9j1Vj8dTOWabw%3D%3D; vtpst=%7C; uidal=5274385825271944%E6%97%A0%E9%87%8F%E7%AB%A5%E5%AD%90; fullscreengg=1; fullscreengg2=1; st_si=66098437338071; emshistory=%5B%22%E6%BD%9E%E5%AE%89%E7%8E%AF%E8%83%BD%22%2C%22undefined%22%5D; HAList=ty-0-000893-%u4E9A%u94BE%u56FD%u9645%2Cty-90-BK0712-%u4E00%u5E26%u4E00%u8DEF%2Cty-1-600171-%u4E0A%u6D77%u8D1D%u5CAD%2Cty-90-BK0854-%u534E%u4E3A%u6982%u5FF5%2Cty-1-601398-%u5DE5%u5546%u94F6%u884C%2Cty-90-BK0968-%u56FA%u6001%u7535%u6C60%2Cty-0-300661-%u5723%u90A6%u80A1%u4EFD%2Cty-90-BK0638-%u521B%u4E1A%u6210%u4EFD%2Cty-1-601699-%u6F5E%u5B89%u73AF%u80FD%2Cty-0-300782-%u5353%u80DC%u5FAE; st_pvi=18633756697256; st_sp=2021-05-13%2015%3A20%3A17; st_inirUrl=https%3A%2F%2Fcn.bing.com%2F; st_sn=96; st_psi=2025041315314915-113300300815-4079987765; st_asi=delete");
                request.setHeader("Host", "push2his.eastmoney.com");
                request.setHeader("Sec-Fetch-Dest", "document");
                request.setHeader("Sec-Fetch-Mode", "navigate");
                request.setHeader("Upgrade-Insecure-Requests", "1");

                // 3. 执行请求并获取响应
                HttpResponse response = httpClient.execute(request);

                // 4. 检查状态码
                //int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("所属类型: " + symbol);

                // 5. 读取响应内容
                HttpEntity entity = response.getEntity();
                if (entity != null) {

                    // 关键：使用 UTF-8 编码转换解压后的字节流
                    String content = EntityUtils.toString(entity, "UTF-8");
                    //toDb(ignite, cache, content, type_name, day);
                    toDb(conn, content, symbol);
                    System.out.println("解码内容:\n" + content);
                }

            } catch (Exception e) {
                System.err.println("请求失败: " + e.getMessage());
            } finally {
                // 6. 释放连接（重要！）
                httpClient.getConnectionManager().shutdown();
            }
        }
    }

    public static void toDb(Connection conn, final String line, String symbol) throws SQLException {
        Pattern pattern = Pattern.compile("\\(([^)]+)\\)");
        Matcher matcher = pattern.matcher(line);

        if (matcher.find()) {
            String result = matcher.group(1); // 获取第一个捕获组内容

            LinkedTreeMap m = MyUtil.getGson().fromJson(result, new TypeToken<LinkedTreeMap>() {}.getType());
            LinkedTreeMap data = (LinkedTreeMap) m.get("data");
            List klines = (List) data.get("klines");
            String name = (String) data.get("name");

            for (int i = klines.size() - 1; i >=  klines.size() - 20; i--) {
                System.out.println(klines.get(i).toString());
                String dl = klines.get(i).toString();
                String[] vs = dl.split(",");
                //List mt = MyUtil.getGson().fromJson(klines.get(i).toString(), new TypeToken<List>() {}.getType());
                if (hasUpdate(conn, symbol, vs[0]) == false) {
                    //String sql = "insert into df_stock_date (symbol, price, main_fund, main_fund_bf, name, zhangdie, stock_date) values ('" + symbol + "', " + vs[11] + ", " + vs[1] + ", " + vs[6] + ", '" + name + "', " + vs[12] + ", '" + vs[0] + "')";
                    //cache.query(new SqlFieldsQuery(sql)).getAll();
                    // "2025-05-20,11.40,11.39,11.47,11.37,643635,734455265.82,0.88,0.18,0.02,0.33"
                    updateDate(conn, symbol, vs[11], vs[1], vs[6], name, vs[12], vs[0]);
                } else {
                    break;
                }
            }

            List<Object> lst = MaiDian.getData(klines);
            List<MMaiDian> lstmd = new ArrayList<>();

            List<Integer> rs = MaiDian1.get_low_ex(lst);
            for (Integer index : rs) {
                List<Object> row = (List<Object>)lst.get(index);
                //update_mai_dian(conn, symbol, row.get(11).toString(), row.get(0).toString());
                lstmd.add(new MMaiDian(symbol, row.get(11).toString(), false, row.get(0).toString()));
            }

            List<Integer> rs1 = MaiDian1.get_height_ex(lst);
            for (Integer index : rs1) {
                List<Object> row = (List<Object>)lst.get(index);
                //update_mai_dian_h(conn, symbol, row.get(11).toString(), row.get(0).toString());
                lstmd.add(new MMaiDian(symbol, row.get(11).toString(), true, row.get(0).toString()));
            }

            Hashtable<String, Integer> ht = new Hashtable<>();
            int index1 = 0;
            for (int i = klines.size() - 1; i >= 0; i--) {
                //System.out.println(klines.get(i).toString());
                String dl = klines.get(i).toString();
                String[] vs = dl.split(",");
                ht.put(vs[0], index1);
                index1++;
            }

            //lstmd.stream().sorted((a, b) -> {return a.getStock_date() - b.getStock_date();}).collect(Collectors.toList());
            lstmd.stream().forEach(m1 -> {
                try {
                    update_mai_dian(conn, m1.getSymbol(), m1.getPrice(), m1.getH(), m1.getStock_date(), ht.get(m1.getStock_date()));
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            });

            List<Float> lsrs = MaiDian.getK(lst, rs);
            Float price_x = MaiDian.get_price_x(lst, rs, lsrs);
            //System.out.println(price_x);
            update_mai_dian_yc(conn, symbol, price_x.toString());
        }
    }

    public static void update_mai_dian_yc(Connection conn, String symbol, String price) throws SQLException {
        // 修改最后一项的数据
        String pkid = getmai_dian_ycId(conn, symbol);
        if (pkid != null) {
            String sql = "update mai_dian_yc SET price = " + price + " WHERE symbol = '" + pkid + "'";
            //cache.query(new SqlFieldsQuery(sql)).getAll();
            Statement stmt = conn.createStatement();
            stmt.execute(sql);
        } else {
            String sql = "insert into mai_dian_yc (symbol, price) values ('" + symbol + "', " + price + ")";
            //cache.query(new SqlFieldsQuery(sql)).getAll();
            Statement stmt = conn.createStatement();
            stmt.execute(sql);
        }
    }

    /**
     * PK id
     * */
    public static Long getPkId(Connection conn) {
        String sql = "select count(id) from df_stock_date";

        PreparedStatement stmt = null;
        ResultSet rs = null;
        long id = 0L;

        try {
            stmt = conn.prepareStatement(sql);

            // 5. 执行查询并获取结果集
            rs = stmt.executeQuery();

            // 6. 遍历结果集并处理数据
            while (rs.next()) {
                id = rs.getLong(1);
            }

        } catch (SQLException e) {
            System.err.println("数据库操作失败！错误信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 7. 关闭资源（反向顺序）
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return id;
    }

    /**
     * 判断 symbol 的数量是否是 20，如果不是 20，就修改最后一项的数据
     * "2025-05-20,11.40,11.39,11.47,11.37,643635,734455265.82,0.88,0.18,0.02,0.33"
     * price = vs[4]
     * main_fund = vs[4]
     * */
    public static void updateDate(Connection conn, String symbol, String price, String main_fund, String main_fund_bf, String name, String zhangdie, String stock_date) throws SQLException {
        Long symbolCount = getSymbolCount(conn, symbol);
        if (symbolCount <= 20) {
            Statement stmt = null;

            if (symbolCount < 20) {
                Long id = getPkId(conn) + 1;
                String sql = "insert into df_stock_date (id, symbol, price, main_fund, main_fund_bf, name, zhangdie, stock_date) values (" + id + ", '" + symbol + "', " + price + ", " + main_fund + ", " + main_fund_bf + ", '" + name + "', " + zhangdie + ", '" + stock_date + "')";
                //cache.query(new SqlFieldsQuery(sql)).getAll();
                stmt = conn.createStatement();
                stmt.execute(sql);
            } else {
                // 修改最后一项的数据
                Long pkid = getSymbolLastId(conn, symbol);
                String sql = "update df_stock_date SET price = "+ price +", main_fund = "+ main_fund +", main_fund_bf = "+ main_fund_bf +", zhangdie = "+ zhangdie +", stock_date = '"+ stock_date +"' WHERE id = " + pkid.toString();
                //cache.query(new SqlFieldsQuery(sql)).getAll();
                stmt = conn.createStatement();
                stmt.execute(sql);
            }
        }
    }

    /**
     * 获取 Symbol 的个数
     * */
    public static Long getSymbolLastId(Connection conn, String symbol) {
        String sql = "select id from df_stock_date where symbol = '"+ symbol +"' ORDER BY stock_date asc LIMIT 0, 1";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        long id = 0L;

        try {
            stmt = conn.prepareStatement(sql);

            // 5. 执行查询并获取结果集
            rs = stmt.executeQuery();

            // 6. 遍历结果集并处理数据
            while (rs.next()) {
                id = rs.getLong(1);
            }

        } catch (SQLException e) {
            System.err.println("数据库操作失败！错误信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 7. 关闭资源（反向顺序）
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return id;
    }

    /**
     * 获取 Symbol 的个数
     * */
    public static Long getSymbolCount(Connection conn, String symbol) {
        String sql = "select count(id) from df_stock_date where symbol = '"+ symbol +"'";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        long id = 0L;

        try {
            stmt = conn.prepareStatement(sql);

            // 5. 执行查询并获取结果集
            rs = stmt.executeQuery();

            // 6. 遍历结果集并处理数据
            while (rs.next()) {
                id = rs.getLong(1);
            }

        } catch (SQLException e) {
            System.err.println("数据库操作失败！错误信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 7. 关闭资源（反向顺序）
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return id;
    }

    public static boolean hasUpdate(Connection conn, String symbol, String stock_date) {

        String sql = "select symbol from df_stock_date where symbol = ? and stock_date = '"+ stock_date +"'";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        boolean id = false;

        try {
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, symbol);

            // 5. 执行查询并获取结果集
            rs = stmt.executeQuery();

            // 6. 遍历结果集并处理数据
            while (rs.next()) {
                id = true;
                break;
            }

        } catch (SQLException e) {
            System.err.println("数据库操作失败！错误信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 7. 关闭资源（反向顺序）
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return id;
    }

    public static int getInt() {
        java.util.Date date = new Date(); // 当前时间

        // 将时间戳（long）强制转换为 int（需谨慎，可能溢出）
        int timestamp = (int) date.getTime();

        System.out.println("时间戳（int）: " + timestamp);
        return timestamp;
    }

    public static void update_mai_dian(Connection conn, String symbol, String price, Boolean h, String stock_date, Integer m_index) throws SQLException {
        // 修改最后一项的数据
        Long pkid = getmai_dianId(conn, symbol, stock_date);
        if (pkid > 0L) {
            String sql = "update mai_dian SET price = " + price + ", stock_date = '" + stock_date + "', m_index = "+ m_index.toString() +" WHERE id = " + pkid.toString();
            //cache.query(new SqlFieldsQuery(sql)).getAll();
            Statement stmt = conn.createStatement();
            stmt.execute(sql);
        } else {
            String sql = "insert into mai_dian (id, symbol, price, h, stock_date, m_index) values (" + getmai_dianLastId(conn) + ", '" + symbol + "', " + price + ", "+ h +", '" + stock_date + "', "+ m_index.toString() +")";
            //cache.query(new SqlFieldsQuery(sql)).getAll();
            Statement stmt = conn.createStatement();
            stmt.execute(sql);
        }
    }

    public static void update_mai_dian_h(Connection conn, String symbol, String price, String stock_date) throws SQLException {
        // 修改最后一项的数据
        Long pkid = getmai_dianId_h(conn, symbol, stock_date);
        if (pkid > 0L) {
            String sql = "update mai_dian_h SET price = " + price + ", stock_date = '" + stock_date + "' WHERE id = " + pkid.toString();
            //cache.query(new SqlFieldsQuery(sql)).getAll();
            Statement stmt = conn.createStatement();
            stmt.execute(sql);
        } else {
            String sql = "insert into mai_dian_h (id, symbol, price, stock_date) values (" + getmai_dianLastId_h(conn) + ", '" + symbol + "', " + price + ", '" + stock_date + "')";
            //cache.query(new SqlFieldsQuery(sql)).getAll();
            Statement stmt = conn.createStatement();
            stmt.execute(sql);
        }
    }

    /**
     * 获取 stock_date 的id
     * */
    public static String getmai_dian_ycId(Connection conn, String symbol) {
        String sql = "select symbol from mai_dian_yc where symbol = '"+ symbol +"'";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        String symbol_id = null;

        try {
            stmt = conn.prepareStatement(sql);

            // 5. 执行查询并获取结果集
            rs = stmt.executeQuery();

            // 6. 遍历结果集并处理数据
            while (rs.next()) {
                symbol_id = rs.getString(1);
            }

        } catch (SQLException e) {
            System.err.println("数据库操作失败！错误信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 7. 关闭资源（反向顺序）
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return symbol_id;
    }

    /**
     * 获取 stock_date 的id
     * */
    public static Long getmai_dianId(Connection conn, String symbol, String stock_date) {
        String sql = "select id from mai_dian where symbol = '"+ symbol +"' and stock_date = '"+ stock_date +"'";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        long id = 0L;

        try {
            stmt = conn.prepareStatement(sql);

            // 5. 执行查询并获取结果集
            rs = stmt.executeQuery();

            // 6. 遍历结果集并处理数据
            while (rs.next()) {
                id = rs.getLong(1);
            }

        } catch (SQLException e) {
            System.err.println("数据库操作失败！错误信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 7. 关闭资源（反向顺序）
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return id;
    }

    public static Long getmai_dianLastId(Connection conn) {
        String sql = "select MAX(id) from mai_dian";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        long id = 0L;

        try {
            stmt = conn.prepareStatement(sql);

            // 5. 执行查询并获取结果集
            rs = stmt.executeQuery();

            // 6. 遍历结果集并处理数据
            while (rs.next()) {
                id = rs.getLong(1);
            }

        } catch (SQLException e) {
            System.err.println("数据库操作失败！错误信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 7. 关闭资源（反向顺序）
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return id + 1L;
    }

    /**
     * 获取 stock_date 的id
     * */
    public static Long getmai_dianId_h(Connection conn, String symbol, String stock_date) {
        String sql = "select id from mai_dian_h where symbol = '"+ symbol +"' and stock_date = '"+ stock_date +"'";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        long id = 0L;

        try {
            stmt = conn.prepareStatement(sql);

            // 5. 执行查询并获取结果集
            rs = stmt.executeQuery();

            // 6. 遍历结果集并处理数据
            while (rs.next()) {
                id = rs.getLong(1);
            }

        } catch (SQLException e) {
            System.err.println("数据库操作失败！错误信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 7. 关闭资源（反向顺序）
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return id;
    }

    public static Long getmai_dianLastId_h(Connection conn) {
        String sql = "select MAX(id) from mai_dian_h";
        PreparedStatement stmt = null;
        ResultSet rs = null;
        long id = 0L;

        try {
            stmt = conn.prepareStatement(sql);

            // 5. 执行查询并获取结果集
            rs = stmt.executeQuery();

            // 6. 遍历结果集并处理数据
            while (rs.next()) {
                id = rs.getLong(1);
            }

        } catch (SQLException e) {
            System.err.println("数据库操作失败！错误信息：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 7. 关闭资源（反向顺序）
            try {
                if (rs != null) rs.close();
                if (stmt != null) stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return id + 1L;
    }
}

